package com.ly.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ly.entity.User;
import com.ly.pojo.dto.LoginDTO;
import com.ly.pojo.dto.RegisterDTO;
import com.ly.pojo.dto.UserDTO;
import com.ly.pojo.dto.updPwdDTO;
import com.ly.pojo.vo.UserVO;
import com.ly.service.UserService;
import com.ly.utils.ExcludeToken;
import com.ly.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : 黑渊白花
 * @ClassName UserController
 * @date : 2025/2/8 17:52
 * @Description
 */
@CrossOrigin //解决跨域问题
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    //用户登录
    @PostMapping("/login")
    @ExcludeToken
    public Result Login(@RequestBody LoginDTO loginDTO){
        UserVO userVO = userService.login(loginDTO);
        return Result.success(userVO);
    }

    @GetMapping("/list")
    public Result list(){
        List<User> users = userService.list();
        return Result.success(users);
    }

    //用户数量
    @GetMapping("/getUserNum")
    public Result getUserNum(){
        long count = userService.count();
        return Result.success(count);
    }
    //用户分页
    @GetMapping("/page")
    public Object page(UserDTO userDTO){
        log.info("{}",userDTO);
        IPage<User> page = userService.getPage(userDTO);
        return page;
    }
    //添加用户的同时保存学生同时将他设置为学生用户type==2（前端传的）
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        userService.saveAndStudent(user);
        return Result.success();
    }

    //修改用户表的userName和name时候同时修改学生表的用户
    //同时判断该用户是否是社长是的话，社团表也要修改
    @PutMapping("/editInfo")
    public Result editInfo(@RequestBody RegisterDTO registerDTO){
        return userService.editInfo(registerDTO);
    }

    //通过id得到用户
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        User user = userService.getById(id);
        return Result.success(user);
    }

    //通过id得到用户
    @PutMapping("/updPwd")
    @ExcludeToken
    public Result updPwd(@RequestBody updPwdDTO pwd){
        Boolean b = userService.updPwd(pwd);
        if(b==false){
            return Result.warn("原密码输入错误！");
        }
        return Result.success("修改成功");
    }

    @PostMapping("/register")
    @ExcludeToken
    public Result register(@RequestBody RegisterDTO registerDTO){
        return userService.register(registerDTO);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user){
        userService.update(user);
        return Result.success();
    }


}
